package com.espressif.iot.ui.main;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

import com.espressif.iot.base.application.EspApplication;
import com.espressif.iot.base.net.rest.mesh.EspSocketClient;
import com.espressif.iot.command.device.plugs.EspCommandPlugsPostStatusInternet;
import com.espressif.iot.command.device.plugs.EspCommandPlugsPostStatusLocal;
import com.espressif.iot.command.device.plugs.IEspCommandPlugsPostStatusInternet;
import com.espressif.iot.command.device.plugs.IEspCommandPlugsPostStatusLocal;
import com.espressif.iot.db.IOTDeviceDBManager;
import com.espressif.iot.db.IOTXqzoneDBManager;
import com.espressif.iot.db.greenrobot.daos.DeviceDB;
import com.espressif.iot.db.greenrobot.daos.XqzoneDB;
import com.espressif.iot.device.IEspDevice;
import com.espressif.iot.device.builder.BEspDevice;
import com.espressif.iot.device.cache.IEspDeviceCache.NotifyType;
import com.espressif.iot.model.device.EspDeviceGateway;
import com.espressif.iot.model.device.cache.EspDeviceCache;
import com.espressif.iot.type.device.EspDeviceType;
import com.espressif.iot.type.net.IOTAddress;
import com.espressif.iot.util.EspStrings.Key;
import com.google.zxing.qrcode.ui.ShareCaptureActivity;
import com.mob.tools.utils.HEX;
import com.xiquezhijia.iot.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnDismissListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Layout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class Xqadddevice extends Activity implements OnClickListener{
	private static final Logger log = Logger.getLogger(Xqadddevice.class);
	private Button back;
	private Button save;
	private TextView zonenametile;
	private EditText devnameedit;
	private EditText devnamefist;
	private EditText devnamethird;
	private EditText devnamefour;
	private View   devinlay;
	private Spinner hostspinner;
	private ToggleButton testonoff;
	//private List<DeviceDB> gatelist = new ArrayList<DeviceDB>();
	String[] gateitem;
	private String zonename; 
	private Set<EspDeviceGateway> gatelist= new HashSet<EspDeviceGateway>();
	
	private  EspSocketClient thiclent =null;
	private  EspDeviceGateway selectedgate;
	
	
	private   byte[] xqplugsenddata = {(byte) 0xFE,(byte) 0xE7,0,0,0x0B,0x00,
			0, 0, 0, 0, 0, 0, 0, 0,//MAC ADDR
			0, 0};
	private   byte[] result;
	private   String sendString = null;
	
	
	private   String devicekey = null;
	private   String bssidstr = null;
	private   String gwbssid = null;
	private   long	 zoneid=0;
	private   XqzoneDB zonedb;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		 
		   
		super.onCreate(savedInstanceState);
		setContentView(R.layout.xqaddplug_activity);
		log.error("onCreate" + zonename );
		
		findView();
		log.error("findView= end");
		
		try {
			initView();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	private void initView() throws IOException {
		// TODO Auto-generated method stub
		// 查找网关个数然后进行加载到hostspinner
		//IOTDeviceDBManager devicemanagerInstance = IOTDeviceDBManager.getInstance();
		gatelist.addAll(EspApplication.GetGlobalGW());
		gateitem = new String[gatelist.size()];
		
		//遍历 set
		Iterator<EspDeviceGateway> list = gatelist.iterator();
		int i=0;
		while(list.hasNext()){
			EspDeviceGateway iotgate = (EspDeviceGateway) list.next();
			gateitem[i++] = iotgate.getName();
		}
		
		ArrayAdapter<String> _Adapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, gateitem);
		//绑定 Adapter到控件
		hostspinner.setAdapter(_Adapter);
		//hostspinner.
		
		
		
		String selgwname =  hostspinner.getSelectedItem().toString();
		list = gatelist.iterator();
		while(list.hasNext()){
			EspDeviceGateway iotgate = (EspDeviceGateway) list.next();
			if(selgwname.equals(iotgate.getName())){
				selectedgate= iotgate;
				gwbssid = selectedgate.getBssid();
				break;
			}
		}
		
		
			if(selectedgate.getInetAddress() !=null)
			{
				
				//new connetsocket(this).execute(false);
				new ConnetSocet().start();
				
			}
					
		
		Intent mintent = getIntent();
		zonename = mintent.getStringExtra(Key.XQZONENAME_KEY);
		zonenametile.setText(zonename);
		IOTXqzoneDBManager zonemanager = IOTXqzoneDBManager.getInstance();
		XqzoneDB zonedb = zonemanager.getzoneDB(zonename);
		zoneid = zonedb.getId();
		devicekey = mintent.getStringExtra(Key.DEVICE_KEY_KEY);
		bssidstr  = devicekey.substring(0, 16);
		
		byte[]  bssid = HEX.decodeHexString(bssidstr);
		bssidstr = "";
		for(int j=0; j<8; j++){
			bssidstr = bssidstr  + " " + bssid[j];
			xqplugsenddata[6+j]=bssid[j];
		}
		Log.e("222222222plug's bssid", bssidstr);
		
		EspDeviceType deviceType = EspDeviceType.getDevicetypte(devicekey);
     	int serial = deviceType.getSerial();
     	//LayoutParams viewpara = devinlay.getLayoutParams();
     	
		if(serial == EspDeviceType.PLUGTOUCH_2.getSerial()){
			//RelativeLayout.LayoutParams para = new RelativeLayout.LayoutParams(viewpara.width/2, LayoutParams.WRAP_CONTENT);
			//para.addRule(RelativeLayout.CENTER_HORIZONTAL ,RelativeLayout.);
			devnamefist.setVisibility(View.VISIBLE);
			devnamethird.setVisibility(View.GONE);
			devnamefour.setVisibility(View.GONE);
			//devnamefist.setLayoutParams(para);
			//devnameedit.setLayoutParams(para);
			
			
		}else if(serial == EspDeviceType.PLUGTOUCH_3.getSerial())
		{

			devnamefist.setVisibility(View.VISIBLE);
			devnamethird.setVisibility(View.VISIBLE);
			devnamefour.setVisibility(View.GONE);
			
		}else if(serial == EspDeviceType.PLUGTOUCH_4.getSerial())
		{
			Toast.makeText(getApplicationContext(), getString(R.string.esp_configure_direct_result_not_found), Toast.LENGTH_SHORT).show();
			finish() ;
		}else{
			devnamethird.setVisibility(View.GONE);
			devnamefist.setVisibility(View.GONE);
			devnamefour.setVisibility(View.GONE);
		}
		//Log.e("333333333333plug's bssid", bssidstr);
	}
	private class ConnetSocet extends Thread{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			thiclent = new EspSocketClient();
			thiclent.connect(selectedgate.getInetAddress().getHostAddress(), 1206);
			
		}
		
	}
	private class ClosetSocet extends Thread{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			try {
				if(thiclent!=null)
				thiclent.close();
				thiclent =null;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	 private class Plugonoff extends AsyncTask<Boolean, Void, Boolean> implements OnDismissListener
	    {
	        private Activity mActivity;
	        
	        private ProgressDialog mDialog;
	        
	        private int mCommand;
	        
	        private Boolean mBroadcast;
	        private boolean conneted;
	        
	        public Plugonoff(Activity activity)
	        {
	            mActivity = activity;
	           
	        }
	        
	       
	        @Override
	        protected void onPreExecute()
	        {
	           
	            
	            showDialog();
	        }
	        
	        @Override
	        protected Boolean doInBackground(Boolean... ison)
	        {
	        	Log.e("getInetAddress", "selectedgate.getInetAddress().getHostName()=" + selectedgate.getInetAddress().getHostAddress());
	        	try {
					thiclent.writeRequest(sendString);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	        	return conneted;
	        }
	        
	        @Override
	        protected void onPostExecute(Boolean result)
	        {
	            //log.debug("DeviceTask result = " + result);
	            releaseDialog();
	           
	            
	        }
	        
	        private void showDialog()
	        {
	            mDialog = new ProgressDialog(mActivity);
	            mDialog.setMessage(getString(R.string.esp_device_task_dialog_message));
	            mDialog.setCanceledOnTouchOutside(false);
	            mDialog.setOnDismissListener(this);
	            mDialog.show();
	        }
	        
	        private void releaseDialog()
	        {
	            if (mDialog != null)
	            {
	                mDialog.dismiss();
	                mDialog = null;
	            }
	        }
	        
	        @Override
	        public void onDismiss(DialogInterface dialog)
	        {
	            cancel(true);
	            mDialog = null;
	        }

			
	    }
	
	 private class Deviceonoff extends AsyncTask<Boolean, Void, Boolean> implements OnDismissListener
	    {
	        private Activity mActivity;
	        
	        private ProgressDialog mDialog;
	        
	        private int mCommand;
	        
	        private Boolean mBroadcast;
	        private boolean conneted;
	        
	        public Deviceonoff(Activity activity)
	        {
	            mActivity = activity;
	           
	        }
	        
	       
	        @Override
	        protected void onPreExecute()
	        {
	           
	            
	            showDialog();
	        }
	        
	        @Override
	        protected Boolean doInBackground(Boolean... ison)
	        {
	        	Log.e("getInetAddress", "selectedgate.getInetAddress().getHostName()=" + selectedgate.getInetAddress().getHostAddress());
				thiclent = new EspSocketClient();
				conneted = thiclent.connect(selectedgate.getInetAddress().getHostAddress(), 1206);
				return conneted;
	        }
	        
	        @Override
	        protected void onPostExecute(Boolean result)
	        {
	            //log.debug("DeviceTask result = " + result);
	            releaseDialog();
	           
	            
	        }
	        
	        private void showDialog()
	        {
	            mDialog = new ProgressDialog(mActivity);
	            mDialog.setMessage(getString(R.string.esp_device_task_dialog_message));
	            mDialog.setCanceledOnTouchOutside(false);
	            mDialog.setOnDismissListener(this);
	            mDialog.show();
	        }
	        
	        private void releaseDialog()
	        {
	            if (mDialog != null)
	            {
	                mDialog.dismiss();
	                mDialog = null;
	            }
	        }
	        
	        @Override
	        public void onDismiss(DialogInterface dialog)
	        {
	            cancel(true);
	            mDialog = null;
	        }

			
	    }
	private void findView() {
		// TODO Auto-generated method stub
		back = (Button)findViewById(R.id.left_icon);
		save = (Button)findViewById(R.id.right_icon);
		devnameedit = (EditText)findViewById(R.id.editdevname);
		hostspinner = (Spinner)findViewById(R.id.gatespinner);
		testonoff = (ToggleButton)findViewById(R.id.testonoff);
		zonenametile = (TextView)findViewById(R.id.zonename);
		
		back.setOnClickListener(this);
		save.setOnClickListener(this);
		testonoff.setOnClickListener(this);
		
		devinlay = (View)findViewById(R.id.deviinfolayout);
		devnamefist = (EditText)findViewById(R.id.editdevfirst);
		devnamethird= (EditText)findViewById(R.id.editdevthird);
		devnamefour= (EditText)findViewById(R.id.editdevfour);
//		devnamefist.setVisibility(View.VISIBLE);
//		devnamethird.setVisibility(View.VISIBLE);
//		devnamefour.setVisibility(View.GONE);
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		if(v == back){
			finish();
		}else if(v == save){
			//关闭socket
			new ClosetSocet().start();
			//需要保存添加进来的配置插座信息到数据库
			
			
			CreatDev2DB();
			EspDeviceCache.getInstance().notifyIUser(NotifyType.STATE_MACHINE_UI);
		finish();	
		}else if(v == testonoff){
			boolean isOn = false;
			if(testonoff.isChecked()){
				isOn = true;
			}else
			{
				isOn = false;
			}
			xqplugsenddata[14] = (byte) ((isOn==true)?1:0);
			byte cheksum=0;
			for(int i=4; i<15; i++){
				cheksum += xqplugsenddata[i]; 
			}
			xqplugsenddata[15] = cheksum;
			
			if(thiclent !=null){
				
				try {
					sendString = new String( xqplugsenddata , "ISO-8859-1" );
				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				new Plugonoff(this).execute(isOn);
				
				
		    	
     			//开始接受数据进行判断处理
//     			String ret =null;
//     			
//     			try {
//					ret=	thiclent.readResponse();
//				} catch (IOException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
//     			
//     			try {
//					result = ret.getBytes("ISO-8859-1");
//				} catch (UnsupportedEncodingException e) {
//					// TODO Auto-generated catch block
//					e.printStackTrace();
//				}
			}
		}
	}
/**
 * IEspDevice alloc(String deviceName, long deviceId, String deviceKey, boolean isOwner, String bssid, int state,
        int ptype, String rom_version, String latest_rom_version, long userId, long... timestamp);
    
 * */
	private void CreatDev2DB() {
		// TODO Auto-generated method stub
		IEspDevice device = null;
		String devname = devnameedit.getText().toString();
		//String txt = devnameedit.getText().toString();
		if(TextUtils.isEmpty(devname)){
			Toast.makeText(getApplicationContext(), getString(R.string.pleaseinputname), Toast.LENGTH_SHORT).show();
			return;
		}
		
		if(devnamefist.getVisibility() ==View.VISIBLE){
			if(TextUtils.isEmpty(devnamefist.getText().toString())){
				Toast.makeText(getApplicationContext(), getString(R.string.pleaseinputname), Toast.LENGTH_SHORT).show();
				return;
			}
			devname = devname + "." + devnamefist.getText().toString();
		}
		if(devnamethird.getVisibility() ==View.VISIBLE){
			if(TextUtils.isEmpty(devnamethird.getText().toString())){
				Toast.makeText(getApplicationContext(), getString(R.string.pleaseinputname), Toast.LENGTH_SHORT).show();
				return;
			}
			devname = devname + "." + devnamethird.getText().toString();
		}
		if(devnamefour.getVisibility() ==View.VISIBLE){
			if(TextUtils.isEmpty(devnamefour.getText().toString())){
				Toast.makeText(getApplicationContext(), getString(R.string.pleaseinputname), Toast.LENGTH_SHORT).show();
				return;
			}
			devname = devname + "." + devnamefour.getText().toString();
		}
		EspDeviceType deviceType = EspDeviceType.getDevicetypte(devicekey);
     	int serial = deviceType.getSerial();
     	byte[] hexdat = HEX.decodeHexString((devicekey.substring(0, 16)));
     	long  devid = ((long)hexdat[0]<<56) + ((long)hexdat[1]<<48) + ((long)hexdat[2]<<40) +
    			((long)hexdat[3]<<32) + ((long)hexdat[4]<<24) + ((long)hexdat[5]<<16)
    			+((long)hexdat[6]<<8) + ((long)hexdat[7]) ;
//		if(serial != EspDeviceType.PLUGTOUCH_2.getSerial() && 
//				serial != EspDeviceType.PLUGTOUCH_3.getSerial() &&
//				serial != EspDeviceType.PLUGTOUCH_4.getSerial())
//     	{
			device =
                BEspDevice.getInstance().alloc(devname, devid, devicekey, false, gwbssid,
                					0, serial, null, null, -1, zoneid);
     	
		if(device ==null){
			Toast.makeText(getApplicationContext(), getString(R.string.esp_configure_direct_result_not_found), Toast.LENGTH_SHORT).show();
			return ;
		}
		device.saveInDB();
	}

}
